<template>
  <div>
    <el-dialog
      :title="info.title"
      :visible.sync="info.show"
      @close="close"
      @open="open"
      style="padding:0;"
      v-dialogDrag
      v-el-drag-dialog
      width="40%"
    >
      <div>
        <el-form :model="uploadData" label-width="100px" ref="uploadFileFrom">
          <el-row align="middle" v-if="isUpload">
            <el-col align="middle">
              <el-upload
                :auto-upload="false"
                :file-list="fileList"
                :on-change="fileChange"
                :show-file-list="false"
                accept=".pdf, .png, .img, .jpeg, .jpg"
                action
                class="upload-demo"
                drag
                multiple
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                  将文件拖到此处，然后
                  <em>点击上传</em>
                </div>
                <div class="el-upload__tip" slot="tip">只能上传pdf/图片文件,最多不超过5MB</div>
              </el-upload>
            </el-col>
          </el-row>
          <el-row align="middle">
            <el-col :key="index" :span="6" v-for="(item,index) in imgFileList">
              <div @click="previewFile('img',imgFileList[index])">
                <el-tooltip :content="item.name" class="item" effect="light" placement="bottom">
                  <img
                    :src="item.src"
                    @click="fileClick('img',index)"
                    alt="图片正在加载"
                    ref="imgPreview"
                    style="width:150px;border: 1px dashed #ccc;margin-left: 10px;"
                  />
                </el-tooltip>
              </div>
              <div
                style="display: flex; justify-content: center; align-items: center;margin-top: 10px;margin-bottom: 10px;"
              >
                <el-button
                  @click="delFile(imgFileList,index)"
                  circle
                  icon="el-icon-delete"
                  size="mini"
                  type="danger"
                  v-if="isUpload"
                ></el-button>
                <el-button circle size="mini" type="warning" v-if="!isUpload"><i @click="downFile(item,pdfFileList,index)" class="el-icon-download"></i></el-button>
              </div>
            </el-col>
          </el-row>
          <el-row align="middle">
            <el-col :key="index" :span="6" v-for="(item,index) in pdfFileList">
              <div @click="previewFile('pdf',pdfFileList[index])">
                <el-tooltip :content="item.name" class="item" effect="light" placement="bottom">
                  <pdf
                    :page="1"
                    :src="item.src"
                    style="width:150px;border: 1px dashed #ccc;margin-left: 10px;"
                  ></pdf>
                </el-tooltip>
              </div>
              <div
                style="display: flex; justify-content: center; align-items: center;margin-top: 10px;margin-bottom: 10px;"
              >
                <el-button
                  @click="delFile(pdfFileList,index)"
                  circle
                  icon="el-icon-delete"
                  size="mini"
                  type="danger"
                  v-if="isUpload"
                ></el-button>
                <el-button circle size="mini" type="warning" v-if="!isUpload"><i @click="downFile(item,pdfFileList,index)" class="el-icon-download"></i></el-button>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <span class="dialog-footer" slot="footer">
        <el-button @click="info.show = false" plain size="mini" type="primary">关 闭</el-button>
        <el-button @click="doUploadFile" size="mini" type="primary">保存</el-button>
      </span>
    </el-dialog>

    <fileView :file-type="viewFileData.fileType" :info="viewFileData"></fileView>
  </div>
</template>

<script>

import pdf from 'vue-pdf'
import fileView from '@/views/cstManagement/twoCstManagement/expenseSettlement/fileView'

export default {
  data() {
    return {
      fileList: [],// 文件数组
      imgFileList: [],
      pdfFileList: [],
      viewFileData: {
        show: false,
        title: '',
        fileType: '',
        file: ''
      },
      fileView: {
        show: false,
        title: ''
      }
    }
  },
  props: {
    info: {
      type: Object,
      required: true
    },
    isUpload: {
      type: Boolean,
      required: true
    }
  },
  components: {
    fileView,
    pdf
  },
  created() {
  },
  mounted() {
  },
  destroyed() {
  },
  methods: {
    open() {
      console.log(this.info.raw)
      if (this.isUpload) {
        this.fileList = this.info.raw.fileList || []
        this.pdfFileList = this.info.raw.pdfFileList || []
        this.imgFileList = this.info.raw.imgFileList || []
        this.pdfFileList.forEach(f => {
          f.src = pdf.createLoadingTask(f.array)
          f.src.promise.then(pdf => {
            f.pdfTotal = pdf.numPages
          })
        })
      } else {
        this.fileList = this.info.raw.annexes
        let url = window._$api.IMAGE_PREFIX
        this.fileList.forEach(file => {
          file.name = file.aname
          const path = file.apath
          if (file.name.endsWith('pdf')) {
            if (process.env.NODE_ENV !== 'production') {
              file.array = '/proxy' + path
            }
            file.src = file.array
            file.src = pdf.createLoadingTask(file.src)
            file.src.promise.then(pdf => {
              file.pdfTotal = pdf.numPages
            })
            this.pdfFileList.push(file)
          } else {
            file.array = path
            file.src = url + path
            this.imgFileList.push(file)
          }
        })
      }
    },
    close() {
      this.fileList = []
      this.imgFileList = []
      this.pdfFileList = []
    },
    fileChange(file, list) {
      file.showName = false
      if (file.size > 5 * 1024 * 1024) {
        this.$message.error('文件大于5MB')
        return
      }
      this.fileList = list
      if (file.raw.type.startsWith('image')) {
        const fr = new FileReader()
        fr.readAsDataURL(file.raw)
        file.width = '150px'
        file.height = '150px'
        fr.onload = () => {
          file.src = fr.result
          this.$nextTick(() => {
            this.imgFileList.push(file)
          })
        }
      }
      if (file.raw.type === 'application/pdf') {
        const fr = new FileReader()
        fr.readAsDataURL(file.raw)
        fr.onload = () => {
          let res = fr.result
          let BASE64_MARKER = ';base64,'
          let base64Index = res.indexOf(BASE64_MARKER) + BASE64_MARKER.length
          let basde64 = res.substring(base64Index).replace(/[\r\n]/g, '')
          const raw = window.atob(basde64)
          const rawLength = raw.length
          const array = new Uint8Array(new ArrayBuffer(rawLength))
          for (let i = 0; i < rawLength; i++) {
            array[i] = raw.charCodeAt(i)
          }
          file.src = {
            data: array
          }
          file.array = array
          file.src = pdf.createLoadingTask(file.src)
          file.src.promise.then(pdf => {
            file.pdfTotal = pdf.numPages
          })
          this.$nextTick(() => {
            this.pdfFileList.push(file)
          })
        }
      }
    },
    previewFile(type, file) {
      if (type === 'pdf') {
        file.src = pdf.createLoadingTask(file.array)
        file.src.promise.then(pdf => {
          file.pdfTotal = pdf.numPages
        })
      }
      this.viewFileData.fileType = type
      this.viewFileData.file = file
      this.viewFileData.title = ''
      this.viewFileData.show = true
    },
    delFile(list, i) {
      list.splice(i, 1)
    },
    doUploadFile() {
      if (this.fileList.length === 0) {
        this.$message.error('请至少选择一个文件')
        return
      }
      this.info.raw.fileList = this.fileList
      this.info.raw.pdfFileList = this.pdfFileList
      this.info.raw.imgFileList = this.imgFileList
      this.info.show = false
    },
    downFile(file, list, index) {
      this.$emit('downFile', file.aid)
    }
  }
}
</script>

<style lang="scss" scoped>
  .file-name {
    font-size: 10px;
  }
</style>
